﻿using System;
using System.Collections.Generic;
using System.Text;

using ET;
using Marx.Utils;

namespace Server
{
    public class RefreshTimer
    {
        private bool running_ = false;
        private ETCancellationToken cancel_ = new ETCancellationToken();
        public async ETTask StartRefreshTimer(TimeSpan during, TimeSpan period, Action action)
        {
            running_ = true;
            try
            {
                DateTime next = TimeUtils.CurDateTime.Add(during);
                await TimerComponent.Instance.WaitAsync((long)during.TotalMilliseconds);
                action();
                if (period > TimeSpan.Zero)
                {
                    while (running_)
                    {
                        next = next.Add(period);
                        bool result = await TimerComponent.Instance.WaitTillAsync(TimeUtils.ToUnixTimestamp(next), cancel_);
                        if(result)
                        {
                            try
                            {
                                action();
                            }
                            catch (Exception e)
                            {
                                Log.Error(e);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                running_ = false;
            }
        }

        public void Cancel()
        {
            running_ = false;
            cancel_.Cancel();
        }
    }
}
